package com.gimi.cloud.jimi.client.service.impl;

import com.gimi.cloud.jimi.client.service.UserService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.common.CommonCoreNoticeService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.core.MessageDao;
import com.gimi.cloud.jimi.dao.dao.core.MessageTemplateDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.sys.AlidayuDTO;
import com.gimi.cloud.jimi.dto.user.UserDTO;
import com.gimi.cloud.jimi.entity.core.Message;
import com.gimi.cloud.jimi.entity.core.MessageTemplate;
import com.gimi.cloud.jimi.entity.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by xiankejin on 2017-10-13
 */
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserDao userDao;
    private final CommonCoreNoticeService coreNoticeService;
    private final IRedisService redisService;
    private final MessageTemplateDao messageTemplateDao;
    private final MessageDao messageDao;


    @Autowired
    public UserServiceImpl(UserDao userDao, CommonCoreNoticeService coreNoticeService,
                           IRedisService redisService, MessageTemplateDao messageTemplateDao, MessageDao messageDao) {
        this.userDao = userDao;
        this.coreNoticeService = coreNoticeService;
        this.redisService = redisService;
        this.messageTemplateDao = messageTemplateDao;
        this.messageDao = messageDao;
    }


    @Override
    public User getUserByMobilePhone(UserDTO userDTO) {
        Example example = new Example(User.class);
        example.createCriteria().andCondition("mobile_phone=", userDTO.getMobilePhone());
        if(userDao.selectByExample(example)!=null && userDao.selectByExample(example).size()>0) {
            return userDao.selectByExample(example).get(0);
        }
        return null;
    }


    @Override
    public User checkPhoneAvailable(String phone) {
        return userDao.checkPhoneAvailable(phone);
    }

    @Override
    public User getUserById(Integer userId) {
        User user = userDao.selectByPrimaryKey(userId);
        return user;
    }


    @Override
    public ResponseCodeEnum sendCode(String phone, String createCode,String typeNid)throws MsgException {
        try {
            // 获取 注册验证码 短信模版内容
            List<MessageTemplate> messageTemplateList = messageTemplateDao.findByNid(typeNid);
            if(messageTemplateList!=null && messageTemplateList.size()>0){
                Map<String, Object> sendData = new HashMap<>();
                sendData.put("code", createCode);
                sendData.put("phone", phone);

                //短信模板内容
                MessageTemplate messageTemplate = messageTemplateList.get(0);
                String tpl_code = messageTemplate.getTplCode();
                //存入消息表中
                Message message = new Message();
                message.setMobile(phone);
                message.setTplId(messageTemplate.getTplId());
                message.setMsgContent(StringUtil.fillTemplet(messageTemplate.getTplContent(),sendData));
                message.setAddTime(new Date());

                // 发送短信方法
                AlidayuDTO alidayuDTO = new AlidayuDTO();
                alidayuDTO.setTemplate(tpl_code);
                alidayuDTO.setPhone(phone);
                Map<String,Object> map = new HashMap<>();
                map.put("code",createCode);
                //map.put("product","米多多");
                alidayuDTO.setParams(JsonUtil.toJson(map));

                long nowTime = new Date().getTime();
                insertResetPwdCodeToRedis(phone, createCode,typeNid);//验证码放入redis中
                logger.info("code:===> "+createCode+", addtime:"+ nowTime);
                //coreNoticeService.sendMessage(message,1,createCode,tpl_code);
                return coreNoticeService.sendSmsByAliDaYu(message,alidayuDTO);
            }else{
                throw new MsgException(ResponseCodeEnum.ERR_SENT_MSG_FAIL, "没有可用的短信模板");
            }
        } catch (Exception e) {
            throw new MsgException(ResponseCodeEnum.ERR_SENT_MSG_FAIL, "短信发送失败");
        }
    }


    @Override
    public User modifyPwd(User user) {
        return userDao.modifyPwd(user.getPwd(),user.getUserId()+"");
    }

    @Override
    public Boolean redisFixedTimeSendCode(String phone) {
        try {
            String key = RedisKeyEnum.JIMI_APP_PRE.getKey()+"verification_code:register:" + phone;
            String redisValue = redisService.get(key);
            if(!StringUtil.isBlank(redisValue)){
                Map<String,String> data = JsonUtil.jsonToMap(redisValue);
                String addTimeStr = data.get("addTime");
                if(!StringUtil.isBlank(addTimeStr)){
                    Long addTime = Long.parseLong(addTimeStr);
                    if (addTime != null && (System.currentTimeMillis() - addTime < 60000L)) {
                        return true;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void insert(User user) {
         userDao.insert(user);
    }

    @Override
    public int insertReturnUserId(User isUser) {
        return userDao.insertReturnUserId(isUser);
    }


    @Override
    public Boolean redisFixedTimeSendModifypasswordCode(String mobilePhone) {
        try {
            String key = RedisKeyEnum.JIMI_APP_PRE.getKey()+"verification_code:modifyPassword:" + mobilePhone;
            String redisValue = redisService.get(key);
            if(!StringUtil.isBlank(redisValue)){
                Map<String,String> data = JsonUtil.jsonToMap(redisValue);
                String addTimeStr = data.get("addTime");
                if(!StringUtil.isBlank(addTimeStr)){
                    Long addTime = Long.parseLong(addTimeStr);
                    if (addTime != null && (System.currentTimeMillis() - addTime < 60000L)) {
                        return true;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void update(User user) {
        userDao.updateByPrimaryKey(user);
    }


    private void insertResetPwdCodeToRedis(String phone,String createCode,String typeNid){
        Map<String,String> data = new HashMap<>();
        String key = RedisKeyEnum.JIMI_APP_PRE.getKey()+"verification_code:"+typeNid+":" + phone;
        data.put("phone",phone);
        data.put("code",createCode);
        data.put("addTime",String.valueOf(System.currentTimeMillis()));
        redisService.set(key,JsonUtil.toJson(data));
        redisService.expire(key,60 * 30);
    }
}
